import { ref } from "vue";
import { usePagination } from "./page";
import { debounce } from "lodash-es";
/**
 * @description 基础表格结构接口封装-用于表格或者下拉
 * @param fn 后端API函数
 * @param params 筛选条件 需要用Ref基类包含对象
 * @param extraConfig 额外设置
 *
 */

export interface ExtraConfig {
  delay?: number; // 防抖时间
  immediate?: boolean;// 是否立即执行一次
  auto?: boolean; // 自动监测参数变化
}

export function useBaseList<T extends (...args:any[])=> any>(
  fn: T,
  params?: Parameters<T>,
  extraConfig?: ExtraConfig,
) {
  if(!extraConfig){
    extraConfig = { delay: 200, immediate: false, auto: false };
  } else {
    extraConfig = Object.assign({ delay: 200, immediate: false, auto: false }, extraConfig);
  }
  const listData = ref<any[]>([]);
  const { getList, pageState, MyPagination, loading } = usePagination(
    async (pageNumber, pageSize) => {
      const params0 = params?.[0];
      if(params0){
        Object.assign(params0, { page:pageNumber,
          pageSize });
      }

      return fn(...(params || [{ page:pageNumber,
        pageSize }])).then((res) => {
        if (res.code === 20000) {
          listData.value =
          Array.isArray(res.data)
            ? res.data
            : res.data?.items || [];
          return { total: res.data?.total, totalPages: res.data?.totalPages };
        }
        return { total: 0 };
      });
    },
  );

  const debounceGetList = debounce(getList, extraConfig.delay);

  if (extraConfig.immediate) {
    debounceGetList();
  }
  // watchEffect(() => {
  //   console.log("watchEffect---",11);
  //   getList()
  // })
  
  return {
    listData,
    getList: debounceGetList,
    pageState,
    MyPagination,
    loading,
  };
}
